<template>
  <div >
    <a-form :model="flowConditionForm" label-width="90px" size="mini" @submit.native.prevent>
      <a-form-item label="流转类型">
        <a-select v-model="flowConditionForm.type" @change="updateFlowType">
          <el-option label="普通流转路径" value="normal" />
          <el-option label="默认流转路径" value="default" />
          <el-option label="条件流转路径" value="condition" />
        </a-select>
      </a-form-item>
      <el-form-item label="条件格式" v-if="flowConditionForm.type === 'condition'" key="condition">
        <el-select v-model="flowConditionForm.conditionType">
          <el-option label="表达式" value="expression" />
        </el-select>
      </el-form-item>
      <el-form-item label="" v-if="flowConditionForm.type === 'condition'" >
        <span slot="label">
                  <el-tooltip content="注意查看参数设置说明" placement="top">
                  <i class="el-icon-question"></i>
                  </el-tooltip>
                  条件格式
                </span>
        <el-select v-model="expressionType.type">
          <el-option label="" value="" />
          <el-option label="" value="" />
          <el-option label="" value="" />
          <el-option label="" value="" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="expressionType.type==='params'" label="参数说明:" >
        <span style="color: darkorange">参数模式，可以是表单中的字段，或者外部传入的自定义的参数，表达式格式举例:${jine>100};</span>
      </el-form-item>
      <template v-if="expressionType.type==='sql'">
        <el-form-item  label="sql语句:" >
          <el-input v-model="expressionType.sqlBody" clearable />
        </el-form-item>
        <el-form-item  label="参数说明:" >
          <el-form-item>
            <span style="color: darkorange">sql模式，编写select语句，并返回count结果，编写表达式，表达式格式举例：${count>5};</span>
          </el-form-item>
          <el-form-item>
            <span style="color: darkorange">select语句中，可以增加表单字段参数或者流程参数;</span>
          </el-form-item>
          <el-form-item>
            <span style="color: darkorange">表单字段参数，即节点中绑定的表单中的字段，不包括子表字段、附件等组件;</span>
          </el-form-item>
          <el-form-item>
            <span style="color: darkorange">流程参数，包括businessKey（表单业务id）、proce_inst_id（流程实例id）、taskid（任务id）、processKey（流程key）;</span>
          </el-form-item>
          <el-form-item>
            <span style="color: darkorange">select语句格式，select username from sys_user where name='@RYMC';</span>
          </el-form-item>
        </el-form-item>
      </template>
      <template v-if="expressionType.type==='webApi'">
        <el-form-item  label="接口地址:" >
          <el-input v-model="expressionType.webApiBody" clearable />
        </el-form-item>
        <el-form-item  label="参数说明:" >
          <el-form-item>
            <span style="color: darkorange">表单字段参数，即节点中绑定的表单中的字段，不包括子表字段、附件等组件;</span>
          </el-form-item>
          <el-form-item>
            <span style="color: darkorange">流程参数，包括businessKey（表单业务id）、proce_inst_id（流程实例id）、taskid（任务id）、processKey（流程key）;</span>
          </el-form-item>
        </el-form-item>

      </template>

      <el-form-item label="表达式" v-if="flowConditionForm.conditionType
      && flowConditionForm.conditionType === 'expression'
                    && expressionType.type!='bySelect'" key="express">
        <el-input v-model="flowConditionForm.body" clearable @change="updateFlowCondition" />
      </el-form-item>
      <el-form-item  label="设置说明:" >
        <span style="color: darkorange">表达式设置或修改后，需要保存发布才可生效；其他修改无需发布</span>
      </el-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'FlowCondition' })
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import { getFlowCond,setFlowCond } from "@bs/process/flowConde";
import { messageC } from '@/util/common'

const props = defineProps<{
  businessObject: Object,
  condElement: Object
}>()

const flowConditionForm = ref({})
const expressionType = ref({
  type:'',
  sqlBody:'',
  webApiBody:''
})

const flowConditionRef = ref(null)
const bpmnElement = ref(null)
const bpmnElementSource = ref(null)
const bpmnElementSourceRef = ref(null)

const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '90px',
  colon: false
}

let depOptions = ref([])
let depUserOptions = ref([])
let userList = ref([])

let showSelUser = ref<boolean>(false)
const formEls: Array<_IFormEl> = reactive([
  { label: '流转类型', key: 'type', col: { span: 24 }, element: 'select',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: [
        {label: '普通流转路径', value: 'normal'},
        {label: '默认流转路径', value: 'default'},
        {label: '条件流转路径', value: 'condition'},
      ]
    }
  },
  { label: '条件格式', key: 'conditionType', col: { span: 24, }, element: 'select',
    formItemProps: { ...formItemProps, required: true },
    hide: computed(() => flowConditionForm.value.type !== 'condition')
    componentProps: {
      options: [
        {label: '表达式', value: 'expression'},
      ]
    },
  },
  { label: '表达式', key: 'body', col: { span: 24 }, element: 'input',
    formItemProps: { ...formItemProps, required: true },
    hide: computed(() => flowConditionForm.value.conditionType && 
      flowConditionForm.value.conditionType === 'expression' && 
      expressionType.value.type != 'bySelect'
    ),
    componentProps: {
      onChange: (e) => {
        updateFlowCondition()
      }
    }
  },
])
const formEls1: Array<_IFormEl> = reactive([
  { label: '条件格式', key: 'conditionType', col: { span: 24, }, element: 'select',
    formItemProps: { ...formItemProps, required: true,
      tooltip: '注意查看参数设置说明'  
    },
    hide: computed(() => flowConditionForm.value.type !== 'condition')
    componentProps: {
      options: [
        {label: '参数模式(表单参数、自定义参数等)', value: 'params'},
        {label: 'SQL模式', value: 'sql'},
        {label: 'WebApi模式', value: 'webApi'},
        {label: '用户选择', value: 'bySelect'},
      ]
    },
  },
  { label: '参数说明', key: 'interapt', col: { span: 24 }, element: 'slot',
    formItemProps: { ...formItemProps, required: true },
    hide: computed(() => expressionType.value.type !=='params')
  },
  { label: 'sql语句', key: 'sqlBody', col: { span: 24 }, element: 'input',
    formItemProps: { ...formItemProps, required: true },
    hide: computed(() => expressionType.value.type !=='sql')
  },
  { label: '参数说明', key: 'interaptSql', col: { span: 24 }, element: 'slot',
    formItemProps: { ...formItemProps, required: true },
    hide: computed(() => expressionType.value.type !=='sql')
  },
  { label: '接口地址', key: 'webApiBody', col: { span: 24 }, element: 'input',
    formItemProps: { ...formItemProps, required: true },
    hide: computed(() => expressionType.value.type !=='webApi')
  },
  { label: '参数说明', key: 'interaptWebapl', col: { span: 24 }, element: 'slot',
    formItemProps: { ...formItemProps, required: true },
    hide: computed(() => expressionType.value.type !=='webApi')
  },
  
])

function resetFlowCondition() {
  bpmnElement.value = this.condElement;
  bpmnElementSource.value = bpmnElement.value.source;
  bpmnElementSourceRef.value = bpmnElement.value.businessObject.sourceRef;
  if (bpmnElementSourceRef.value && bpmnElementSourceRef.value.default && bpmnElementSourceRef.value.default.id === bpmnElement.value.id) {
    // 默认
    flowConditionForm.value = { type: "default" };
  } else if (!bpmnElement.value.businessObject.conditionExpression) {
    // 普通
    flowConditionForm.value = { type: "normal" };
  } else {
    // 带条件
    const conditionExpression = bpmnElement.value.businessObject.conditionExpression;
    flowConditionForm.value = { ...conditionExpression, type: "condition" };
    // resource 可直接标识 是否是外部资源脚本
    if (flowConditionForm.value.resource) {
      flowConditionForm.value.conditionType = "script"
      flowConditionForm.value.scriptType = "externalScript"
      return;
    }
    if (conditionExpression.language) {
      flowConditionForm.value.conditionType = "script"
      flowConditionForm.value.scriptType = "inlineScript"
      return;
    }
    flowConditionForm.value.conditionType = "expression"

    getFlowCond(bpmnElement.value.id).then((res)=>{
      if(res.error == "200" && res.result != undefined) {
        expressionType.value.type = res.result.expression_type;
        if(res.result.expression_type == "sql") {
          expressionType.value.sqlBody = res.result.expression_body;
        }
        if(res.result.expression_type == "webApi") {
          expressionType.value.webApiBody = res.result.expression_body;
        }
      }
    })
  }
}

function updateFlowType(flowType) {
  // 正常条件类
  if (flowType === "condition") {
    flowConditionRef.value = window.bpmnInstances.moddle.create("bpmn:FormalExpression");
    window.bpmnInstances.modeling.updateProperties(bpmnElement.value, {
      conditionExpression: flowConditionRef.value
    });
    return;
  }
  // 默认路径
  if (flowType === "default") {
    window.bpmnInstances.modeling.updateProperties(bpmnElement.value, {
      conditionExpression: null
    });
    window.bpmnInstances.modeling.updateProperties(bpmnElementSource.value, {
      default: bpmnElement.value
    });
    return;
  }
  // 正常路径，如果来源节点的默认路径是当前连线时，清除父元素的默认路径配置
  if (bpmnElementSourceRef.value.default && bpmnElementSourceRef.value.default.id === bpmnElement.value.id) {
    window.bpmnInstances.modeling.updateProperties(bpmnElementSource.value, {
      default: null
    });
  }
  window.bpmnInstances.modeling.updateProperties(bpmnElement.value, {
    conditionExpression: null
  });
}

function updateFlowCondition() {
  let { conditionType, scriptType, body, resource, language } = flowConditionForm.value;
  let condition;
  if (conditionType === "expression") {
    condition = window.bpmnInstances.moddle.create("bpmn:FormalExpression", { body });
  } else {
    if (scriptType === "inlineScript") {
      condition = window.bpmnInstances.moddle.create("bpmn:FormalExpression", { body, language });
      flowConditionForm.value.resource = ""
    } else {
      flowConditionForm.value.body = ""
      condition = window.bpmnInstances.moddle.create("bpmn:FormalExpression", { resource, language });
    }
  }
  window.bpmnInstances.modeling.updateProperties(bpmnElement.value, { conditionExpression: condition });
}

function save(){
  const queryParams={
    expressionId:bpmnElement.value.id,
    type:expressionType.value.type,
    sqlBody:expressionType.value.sqlBody,
    webApiBody:expressionType.value.webApiBody
  }
  //如果是手动选择
  if(expressionType.value.type==='bySelect'){
    flowConditionForm.value.body="${"+bpmnElement.value.id+">0}";
    updateFlowCondition();
  }
  // setFlowCond(queryParams).then((res) =>{
  //   if (res.error == '200') {
  //     messageC('设置成功', 'success');
  //   } else {
  //     messageC('设置失败');
  //   }
  // })
}

watch(() => props.businessObject, (nval, oval) => {
  nextTick(() => resetFlowCondition());
}, { immediate: true })

onUnmounted(() => {
  bpmnElement.value = null;
  bpmnElementSource.value = null;
  bpmnElementSourceRef.value = null;
})
</script>
